package com.zhimeng.personal;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.zhimeng.personal.data.DataCenter;
import com.zhimeng.personal.utils.ToastUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

/**
 * Created by sunzhimeng on 11/1/17.
 */

public class MyApplication extends Application{

    private Context applicationContext;

    @Override
    public void onTerminate() {
        exitApp();
        super.onTerminate();
    }

    public void exitApp() {
        System.gc();
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    @Override
    public void onCreate() {
        super.onCreate();
        applicationContext = this;
        ToastUtils.register(this);
        DataCenter.register(this);
    }

    public String sHA1() {
        try {
            PackageInfo info = applicationContext.getPackageManager().getPackageInfo(
                    applicationContext.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length()-1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
